package com.lightboat.web.controller.crm;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lightboat.common.annotation.Log;
import com.lightboat.common.core.controller.BaseController;
import com.lightboat.common.core.domain.AjaxResult;
import com.lightboat.common.core.page.TableDataInfo;
import com.lightboat.common.enums.BusinessType;
import com.lightboat.common.utils.DateUtils;
import com.lightboat.common.utils.PageUtils;
import com.lightboat.common.utils.SecurityUtils;
import com.lightboat.common.utils.poi.ExcelUtil;
import com.lightboat.system.domain.CrmUserFollowRecord;
import com.lightboat.system.service.ICrmUserFollowRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户跟进记录Controller
 *
 * @author lightboat
 * @date 2025-08-22
 */
@Tag(name = "用户跟进记录")
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/follow/record")
public class CrmUserFollowRecordController extends BaseController {

    private final ICrmUserFollowRecordService crmUserFollowRecordService;

    /**
     * 查询用户跟进记录列表
     */
    @Operation(summary = "查询用户跟进记录列表")
    @GetMapping("/list/bus")
    public TableDataInfo list(CrmUserFollowRecord crmUserFollowRecord) {
        if (ObjUtil.isEmpty(crmUserFollowRecord.getOrderId()) && ObjUtil.isEmpty(crmUserFollowRecord.getCustomerId())) {
            throw new RuntimeException("请选择客户或订单");
        }
        startPage();
        PageUtils.<CrmUserFollowRecord>chainOrderBy()
                .orderByDesc(CrmUserFollowRecord::getTopStatus).orderByDesc(CrmUserFollowRecord::getTopSort)
                .orderByDesc(CrmUserFollowRecord::getTopTime).orderByDesc(CrmUserFollowRecord::getCreateTime)
                .apply();
        LambdaQueryWrapper<CrmUserFollowRecord> wrapper = crmUserFollowRecordService.getQueryWrapper(crmUserFollowRecord);

        List<CrmUserFollowRecord> list = crmUserFollowRecordService.selectCrmUserFollowRecordList(wrapper);
        clearPage();
        return getDataTable(list);
    }


    /**
     * 查询用户跟进记录列表
     */
    @Operation(summary = "查询全部用户跟进记录列表")
    // @PreAuthorize("@ss.hasPermi('system:record:list')")
    @GetMapping("/list/all")
    public TableDataInfo listAll(CrmUserFollowRecord crmUserFollowRecord) {
        List<CrmUserFollowRecord> list = crmUserFollowRecordService.selectCrmUserFollowRecordList(crmUserFollowRecord);
        return getDataTable(list);
    }

    /**
     * 导出用户跟进记录列表
     */
    @Operation(summary = "导出用户跟进记录列表")
    @PreAuthorize("@ss.hasPermi('system:record:export')")
    @Log(title = "用户跟进记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CrmUserFollowRecord crmUserFollowRecord) {
        List<CrmUserFollowRecord> list = crmUserFollowRecordService.selectCrmUserFollowRecordList(crmUserFollowRecord);
        ExcelUtil<CrmUserFollowRecord> util = new ExcelUtil<CrmUserFollowRecord>(CrmUserFollowRecord.class);
        util.exportExcel(response, list, "用户跟进记录数据");
    }

    /**
     * 获取用户跟进记录详细信息
     */
    @Operation(summary = "获取用户跟进记录详细信息")
    // @PreAuthorize("@ss.hasPermi('system:record:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(crmUserFollowRecordService.selectCrmUserFollowRecordById(id));
    }

    /**
     * 新增用户跟进记录
     */
    @Operation(summary = "新增用户跟进记录")
    // @PreAuthorize("@ss.hasPermi('system:record:add')")
    @Log(title = "用户跟进记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CrmUserFollowRecord crmUserFollowRecord) {
        crmUserFollowRecord.setTopStatus(null);
        crmUserFollowRecord.setIsFollowed(null);
        crmUserFollowRecord.setUserId(getUserId());
        return toAjax(crmUserFollowRecordService.insertCrmUserFollowRecord(crmUserFollowRecord));
    }

    /**
     * 修改用户跟进记录
     */
    @Operation(summary = "修改用户跟进记录")
    // @PreAuthorize("@ss.hasPermi('system:record:edit')")
    @Log(title = "用户跟进记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CrmUserFollowRecord crmUserFollowRecord) {

        LambdaUpdateWrapper<CrmUserFollowRecord> wrapper = Wrappers.<CrmUserFollowRecord>lambdaUpdate()
                .eq(!SecurityUtils.isAdmin(getUserId()), CrmUserFollowRecord::getUserId, getUserId())
                .eq(CrmUserFollowRecord::getId, crmUserFollowRecord.getId());

        if (ObjUtil.isNotEmpty(crmUserFollowRecord.getTopStatus()) && crmUserFollowRecord.getTopStatus() == 1) {
            crmUserFollowRecord.setTopTime(DateUtils.date().toJdkDate());
        }else if (ObjUtil.isNotEmpty(crmUserFollowRecord.getTopStatus()) && crmUserFollowRecord.getTopStatus() == 0) {
            wrapper.set(CrmUserFollowRecord::getTopTime, null);
        }

        boolean update = crmUserFollowRecordService.update(crmUserFollowRecord, wrapper);
        return toAjax(update);
    }

    /**
     * 删除用户跟进记录
     */
    @Operation(summary = "删除用户跟进记录")
    @PreAuthorize("@ss.hasPermi('system:record:remove')")
    @Log(title = "用户跟进记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(crmUserFollowRecordService.deleteCrmUserFollowRecordByIds(ids));
    }
}
